<template>
  <div class="bg-white radius-8px p-20px history-chart">
    <div class="mb-10px history-search">
      <span class="inline-block min-w-70px text-right">产品类型：</span>
      <el-radio-group
          v-model="state.productType"
          name="checkboxgroup"
      >
        <el-radio v-for="(item, index) in state.productTypeOptions" :key="index" :label="item.value" size="large"
                  border>
          {{ item.label }}
        </el-radio>
      </el-radio-group>
    </div>
    <div class="mb-10px history-search" v-if="state.productType === '1'">
      <span class="inline-block min-w-70px text-right">时间：</span>
      <el-radio-group
          v-model="state.dateRange"
          name="radiogroup"
      >
        <el-radio v-for="(item, index) in dateRangeOptions" :key="index" :label="item.value" size="large" border>
          {{ item.label }}
        </el-radio>
      </el-radio-group>
    </div>
    <div v-if="state.productType === '1'">
      <el-row type="flex" class="mb-15px">
        <el-col :span="24">
          <!--心率呼吸图-->
          <HeartBeatChart
              ref="heartBeatChartRef"
              v-if="state.history.historyTime.length > 0"
              :chart-data="state.history"
          />
        </el-col>
      </el-row>
      <el-row type="flex" class="mb-15px">
        <el-col :span="24">
          <!--血压统计图-->
          <BloodPressure
              ref="bloodPressureRef"
              v-if="state.bloodPressure.historyTime.length > 0"
              :chart-data="state.bloodPressure"
          />
        </el-col>
      </el-row>
      <el-row type="flex" :gutter="15" class="mb-15px">
        <el-col :span="12">
          <!--睡眠分期图-->
          <SleepDay ref="sleepDayRef" v-if="state.sleepChart.length > 0 && state.dateRange === 1"
                    :chart-data="state.sleepChart"/>
          <Sleep ref="sleepRef" v-if="state.dateRange > 1" :startTime="state.startTime"
                 :chart-data="state.sleepData" :dateRange="state.dateRange"/>
        </el-col>
        <el-col :span="12">
          <!--HRV、情绪压力图-->
          <Hrv ref="hrvRef" v-if="state.hrv.length > 0" :chart-data="state.hrv" :refresh="state.hrvRefresh"/>
        </el-col>
      </el-row>
      <el-row type="flex" class="mb-15px">
        <el-col :span="24">
          <!--心率呼吸体动曲线图-->
          <HeartRateBreathing ref="heartRateBreathingRef" v-if="state.sleepData.length > 0" :startTime="state.startTime"
                              :sleepData="state.sleepData" :sleepRefresh="state.sleepRefresh"/>
        </el-col>
      </el-row>
    </div>
    <div class="history-bracelet" v-else>
      <Map ref="mapRef" :deviceCode="state.deviceCode"/>
    </div>
  </div>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref, watch} from 'vue';
import {useRoute} from 'vue-router';
import moment from 'moment';

import HeartBeatChart from '../charts/HeartBeat.vue';
import HeartRateBreathing from '../charts/HeartRateAndBreathing.vue';
import BloodPressure from '../charts/BloodPressure.vue';
import SleepDay from '../charts/SleepDay.vue';
import Sleep from '../charts/Sleep.vue';
import Hrv from '../charts/hrv/Hrv.vue';
import Map from '../map/Index.vue';

import {findHrvListApi, listSleepResultApi} from '@/api/sleep';
import {listNursingRecordPageApi} from '@/api/personnel';

const heartBeatChartRef = ref(HeartBeatChart)
const heartRateBreathingRef = ref(HeartRateBreathing)
const bloodPressureRef = ref(BloodPressure)
const sleepDayRef = ref(SleepDay)
const sleepRef = ref(Sleep)
const hrvRef = ref(Hrv)
const mapRef = ref(Map)

const deviceTypeList = ['four_g_watch', 'nb_watch'];
const dateRangeOptions = [
  {label: '今日数据', value: 1},
  {label: '最近7天', value: 2},
  {label: '最近一个月', value: 3},
];
const route = useRoute()
const props = defineProps({
  older: {
    type: Object,
    default: {},
  },
});

//时间
const date = ref(new Date());
const state = reactive({
  productTypeOptions: [
    {label: '床垫', value: '1'},
  ],
  dateRange: 1,
  deviceCode: '',
  productType: '1',
  history: {
    historyTime: [] as any,
    heartbeat: [] as any,
    breathing: [] as any,
    temperature: [] as any,
    bloodOxygen: [] as any,
  },
  bloodPressure: {
    historyTime: [] as any,
    systolic: [] as any,
    diastolic: [] as any,
  } as any,
  hrv: [] as any,
  hrvRefresh: 0 as any,
  sleepChart: [] as any,
  sleepData: [] as any,
  sleepRefresh: null as any,
  startTime: null as any,
});
onMounted(() => {
  const bracelet = props.older.deviceList.find(({deviceType = ''}) => deviceTypeList.includes(deviceType))
  if (bracelet && bracelet.deviceCode) {
    state.deviceCode = bracelet.deviceCode
    state.productTypeOptions.push({label: '手环', value: '2'})
  }
  getChartData();
});
watch(
    () => state.dateRange,
    (dateRange) => {
      state.history = {
        historyTime: [] as any,
        heartbeat: [] as any,
        breathing: [] as any,
        temperature: [] as any,
        bloodOxygen: [] as any,
      };
      state.bloodPressure = {
        historyTime: [] as any,
        systolic: [] as any,
        diastolic: [] as any,
      };
      state.hrv = [];
      state.sleepChart = [];
      getChartData(dateRange);
    },
    {
      // immediate: true,
    },
);
/**
 *获取图表数据
 * */
const getChartData = async (dateRange = 1) => {
  //1 代表查询日 2代表查询周  3代表查询月
  const olderId = route.query.olderId || props.older.id;
  const params = {
    olderId, // 老人id
    unitUserId: olderId, // 老人id
    pageIndex: 1,
    pageSize: 10000,
    dateRange,
  };
  const data = (await listNursingRecordPageApi(params)) || [];
  data.forEach((_) => {
    state.history.historyTime.push(_.recordTime.replace('T', ' '))
    //心率
    state.history.heartbeat.push(_.pulse);
    //呼吸
    state.history.breathing.push(_.breathe);
    //体温
    state.history.temperature.push(_.temperature);
    //血氧
    state.history.bloodOxygen.push(_.oximeter);
    //血压
    if (_.bloodPressure) {
      state.bloodPressure.historyTime.push(_.recordTime.replace('T', ' '))
      const [high, low] = _.bloodPressure.split('/');
      state.bloodPressure.systolic.push(parseInt(high));
      state.bloodPressure.diastolic.push(parseInt(low));
    }
  });
  /**
   * 请求情绪 HRV
   */
  let curDate = moment().format('YYYY-MM-DD HH:mm:ss');
  let curhrDate = curDate;
  let timeRange = 'day' as any;
  switch (dateRange) {
    case 1:
      timeRange = 'day';
      break;
    case 2:
      timeRange = 'week';
      curDate = moment(curDate).add(-6, 'days').format('YYYY-MM-DD HH:mm:ss')
      curhrDate = curDate
      break;
    case 3:
      timeRange = 'month';
      curDate = moment(new Date(curDate).setMonth(new Date(curDate).getMonth() - 1)).format('YYYY-MM-DD HH:mm:ss')
      curhrDate = moment(new Date(curDate).setDate(new Date(curDate).getDate() - 7)).format('YYYY-MM-DD HH:mm:ss')
      break;
  }
  const findHrvListParams = {
    olderId, // 老人id
    unitUserId: olderId, // 老人id
    tstartTime: moment(curDate).format('YYYY-MM-DD 00:00:00'), //开始时间    2022-07-09T14:23:03
    tendTime: moment().format('YYYY-MM-DD 23:59:59'), //结束时间     2022-07-09T14:23:03
  };
  const findHrvList = (await findHrvListApi(findHrvListParams)) || [];
  findHrvList.forEach((_) => {
    if (_.tstartTime && _.hrvTimeDomain5 && _.hrvTimeDomain5.hrv && _.hrvTimeDomain5.hrv !== -1) {
      state.hrv.push({
        name: 'HRV',
        time: _.tstartTime,
        iSleepResultId: _.hrvTimeDomain5.iSleepResultId,
        value: _.hrvTimeDomain5.hrv,
      });
    }
    if (
        _.tstartTime &&
        _.hrvFreqDomain5 &&
        _.hrvFreqDomain5.eindex &&
        _.hrvFreqDomain5.eindex !== -1
    ) {
      state.hrv.push({
        name: '情绪压力',
        time: _.tstartTime,
        iSleepResultId: _.hrvTimeDomain5.iSleepResultId,
        value: _.hrvFreqDomain5.eindex,
      });
    }
  });
  state.hrvRefresh = Math.random()
  console.log('hrv', state.hrv.length)
  /**
   * 请求睡眠
   * */
  const sleepParams = {
    olderId,
    unitUserId: olderId,
    startTime: moment(curhrDate).format('YYYY-MM-DDT00:00:00'),
    endTime: moment().format('YYYY-MM-DDT23:59:59')
  };
  const sleepData = (await listSleepResultApi(sleepParams)) || [];
  state.sleepData = sleepData;
  state.startTime = sleepParams.startTime;
  state.sleepRefresh = Math.random()
  if (state.dateRange > 1) {
    return
  }
  //获取老人床垫类型
  const formCode = ((props.older || {}).mattress || {}).formCode;
  const getSleepLableVo = (num: any) => {
    if (num === 3) {
      return {name: '觉醒', code: 3, color: '#FED64D'};
    } else if (num === 2) {
      return {name: '快速眼动', code: 2, color: '#C5DAFF'};
    } else if (num === 1) {
      return {name: '浅睡', code: 1, color: '#A7D3FE'};
    } else if (num === 0) {
      return {name: '深睡', code: 0, color: '#3AA0FF'};
    } else {
      return {name: '清醒', code: 4, color: '#FF0000'};
    }
  };
  // 结束时间
  const formatTime = 'YYYY/MM/DD HH:mm:ss'
  sleepData.forEach((_, index) => {
    //判断是床垫还是监测带
    if (formCode !== 'detection_band') {
      //床垫
      if (
          _.tSleepDate &&
          _.tEndSleep &&
          _.tFallAsleepTime &&
          _.tWakeTime &&
          (_.iMainSleepFlag == 1 || _.iMainSleepFlag == 101)
      ) {
        const _tStartSleep = moment(_.tStartSleep).valueOf();
        // 当前睡眠值
        let nextCode = -1
        // 开始时间
        let startTime = _tStartSleep
        // 结束时间
        let endTime = _tStartSleep
        // 睡眠角色值
        _.mtSleepStage &&
        _.mtSleepStage.split(',').forEach((num, _index) => {
          const _num = parseInt(num);
          if (!isNaN(_num)) {
            try {
              if (nextCode != _num) {
                if (nextCode != -1) {
                  const {name, code, color} = getSleepLableVo(nextCode);
                  state.sleepChart.push({
                    name,
                    itemStyle: {normal: {color}},
                    value: [code, moment(startTime).format(formatTime), moment(endTime).format(formatTime)],
                  });
                }
                nextCode = _num
                startTime = endTime
              }
              endTime = _tStartSleep + (_index * 45 * 1000);
            } catch (e) {
              console.log('getSleepLableVo', num)
            }
          }
        });

        const {name, code, color} = getSleepLableVo(nextCode);
        state.sleepChart.push({
          name,
          itemStyle: {normal: {color}},
          value: [code, moment(startTime).format(formatTime), moment(endTime).format(formatTime)],
        });
        console.log('mtSleepStage', state.sleepChart)
      }
    } else {
      //检测带  暂不显示
      if (_.tSleepDate && _.tEndSleep) {
        console.log(_.tSleepDate)
      }
    }
  });

  console.log('sleepData', sleepData);
};
</script>